package models.automation;

import models.automation.events.DuplicateFound;
import models.automation.events.ImageFixerProgress;
import models.repository.ImageRepositorySql;
import models.repository.common.ImageRepository;
import play.cache.Cache;

import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

public class ImageFixerObserver implements Observer {
    private ImageRepository repository = new ImageRepositorySql();
    private String webCacheKey;

    public ImageFixerObserver(String cacheKey){
        webCacheKey = cacheKey;
    }
    public void update(Observable o, Object arg) {
        if (arg instanceof ImageFixerProgress) {
            updateProgress((ImageFixerProgress) arg);
        } else if (arg instanceof DuplicateFound){
            try {
                addDuplicate((DuplicateFound)arg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void addDuplicate(DuplicateFound arg) throws IOException {
        repository.addDuplicate(arg.originalImage.id, arg.duplicate.id);
    }

    private void updateProgress(ImageFixerProgress arg) {
        Cache.set(webCacheKey, arg);
    }
}
